/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.sys.utils;

import java.io.*;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.thinkgem.jeesite.common.mapper.JsonMapper;
import com.thinkgem.jeesite.common.utils.CacheUtils;
import com.thinkgem.jeesite.common.utils.SpringContextHolder;
import com.thinkgem.jeesite.modules.sys.dao.DictDao;
import com.thinkgem.jeesite.modules.sys.entity.Dict;

/**
 * 字典工具类
 * @author xiaoming
 * @version 2013-5-29
 */
public class DictUtils {
	
	private static DictDao dictDao = SpringContextHolder.getBean(DictDao.class);

	public static final String CACHE_DICT_MAP = "dictMap";
	
	public static String getDictLabel(String value, String type, String defaultValue){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)){
			for (Dict dict : getDictList(type)){
				if (type.equals(dict.getType()) && value.equals(dict.getValue())){
					return dict.getLabel();
				}
			}
		}
		return defaultValue;
	}
	
	public static String getDictLabels(String values, String type, String defaultValue){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(values)){
			List<String> valueList = Lists.newArrayList();
			for (String value : StringUtils.split(values, ",")){
				valueList.add(getDictLabel(value, type, defaultValue));
			}
			return StringUtils.join(valueList, ",");
		}
		return defaultValue;
	}

	public static String getDictValue(String label, String type, String defaultLabel){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(label)){
			for (Dict dict : getDictList(type)){
				if (type.equals(dict.getType()) && label.equals(dict.getLabel())){
					return dict.getValue();
				}
			}
		}
		return defaultLabel;
	}
	public static List<Dict> getDictList(String type){
		return  getDictListByIds(type,null);
	}

	public static List<Dict> getDictListByIds(String type,String ids){
		Map<String, List<Dict>> dictMap = (Map<String, List<Dict>>)CacheUtils.get(CACHE_DICT_MAP);
		if (dictMap==null){
			dictMap = Maps.newHashMap();
			for (Dict dict : dictDao.findAllList(new Dict())){
				List<Dict> dictList = dictMap.get(dict.getType());
				if (dictList != null){
					dictList.add(dict);
				}else{
					dictMap.put(dict.getType(), Lists.newArrayList(dict));
				}
			}
			CacheUtils.put(CACHE_DICT_MAP, dictMap);
		}
		List<Dict> dictList = dictMap.get(type);
		if(ids!=null && !"".equals(ids)){
			List<Dict> param=new ArrayList<>();
			for(String id:ids.split(",")){
				for(Dict t:dictList){
					if(t.getValue().equals(id))
						param.add(t);
				}
			}
			dictList=param;
		}
		if (dictList == null){
			dictList = Lists.newArrayList();
		}
		return dictList;
	}
	
	/**
	 * 返回字典列表（JSON）
	 * @param type
	 * @return
	 */
	public static String getDictListJson(String type){
		return JsonMapper.toJsonString(getDictList(type));
	}

	public static Map getRemarkMapper(String type,String id){
		List<Dict> list= DictUtils.getDictListByIds(type,id);
		String s=list.get(0).getRemarks().replaceAll("&quot;","\"");
		return  (Map) JsonMapper.fromJsonString(s,Map.class);
	}

	public static String getValue(String str,String key){
		String s = str.replaceAll("&quot;", "\"");
		Map<String,String> maps = (Map) JsonMapper.fromJsonString(s,Map.class);
		return maps.get(key);
	}

	/**
	 * 实现集合的深度复制①
	 * note: T.class 必须实现序列化
	 * @param src
	 * @param <T>
	 * @return
	 * @throws IOException
	 * @throws ClassNotFoundException
	 */
	public static <T> List<T> deepCopyCollectionBySerialize(List<T> src) throws IOException, ClassNotFoundException {
		ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
		ObjectOutputStream out = new ObjectOutputStream(byteOut);
		out.writeObject(src);

		ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
		ObjectInputStream in = new ObjectInputStream(byteIn);
		List<T> dest = (List<T>) in.readObject();
		return dest;
	}

	/**
	 * 实现集合的深度复制②
	 * 通用版
	 * @param source
	 * @param clazz
	 * @param <T>
	 * @return
	 */
	public static <T> ArrayList<T> deepCopyCollectionByJson(List<T> source, Class<T> clazz) {
		Gson gson = new Gson();
		String json = gson.toJson(source);
		Type type = new TypeToken<ArrayList<JsonElement>>() {}.getType();
		ArrayList<JsonElement> jsonElements = gson.fromJson(json, type);

		ArrayList<T> arrayList = new ArrayList<>();
		for (JsonElement jsonElement : jsonElements) {
			arrayList.add(gson.fromJson(jsonElement, clazz));
		}
		return arrayList;
	}


	public static String getDictUnit(String value, String type){
		if (StringUtils.isNotBlank(type) && StringUtils.isNotBlank(value)){
			for (Dict dict : getDictList(type)){
				if (type.equals(dict.getType()) && value.equals(dict.getValue())){
					return DictUtils.getValue(dict.getRemarks(), "unit");
				}
			}
		}
		return "";
	}
}
